"""
Sperm Bank Management System - Backend API
Main application entry point
"""

from flask import Flask, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
import os

# Import routes
from routes import donors, sperm_vials, recipients, orders, shipments, clinics, staff, statistics, offspring

# Load environment variables
load_dotenv()

# Create Flask app
app = Flask(__name__)

# CORS configuration
CORS(app, resources={
    r"/api/*": {
        "origins": [
            "http://113.249.105.168",
            "http://113.249.105.168:2025",  # 公网访问端口
            "http://113.249.105.168:8080",  # 默认端口
            "http://113.249.105.168:3000",  # 备用端口
            "http://localhost:5173",  # Vite开发服务器
            "http://localhost:3000",  # 备用开发端口
            "http://localhost:8080"   # 本地Nginx
        ],
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type", "Authorization"]
    }
})

# Register blueprints (API routes)
app.register_blueprint(donors.bp)
app.register_blueprint(sperm_vials.bp)
app.register_blueprint(recipients.bp)
app.register_blueprint(orders.bp)
app.register_blueprint(shipments.bp)
app.register_blueprint(clinics.bp)
app.register_blueprint(staff.bp)
app.register_blueprint(statistics.bp)
app.register_blueprint(offspring.bp)

# Health check endpoint
@app.route('/api/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        'status': 'ok',
        'message': 'Sperm Bank Management System API is running'
    }), 200

# Root endpoint
@app.route('/')
def index():
    """Root endpoint"""
    return jsonify({
        'message': 'Sperm Bank Management System API',
        'version': '1.0.0',
        'endpoints': {
            'health': '/api/health',
            'donors': '/api/donors',
            'vials': '/api/vials',
            'recipients': '/api/recipients',
            'orders': '/api/orders',
            'shipments': '/api/shipments',
            'clinics': '/api/clinics',
            'staff': '/api/staff',
            'statistics': '/api/statistics',
            'offspring': '/api/offspring'
        }
    }), 200

# Error handlers
@app.errorhandler(404)
def not_found(error):
    return jsonify({'code': 404, 'message': 'Resource not found', 'data': None}), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({'code': 500, 'message': 'Internal server error', 'data': None}), 500

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))
    debug = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
    
    app.run(
        host='0.0.0.0',
        port=port,
        debug=debug
    )

